<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>弹幕墙</title>
    <style media="screen">
        html,
        body {
            margin: 0;
            padding: 0;
        }

        body {
            margin-top: 1em;
            padding: 0 1em;
        }

        .screen {
            border: 4px solid #999;
            height: 24em;
            padding-top: 1em;
        }

        .word-row {
            /*background-color: #eee;*/
            font-size: 3em;
            margin-bottom: 0.5em;
        }

        .word-row {
            position: relative;
            height: 1.15em;
            overflow: hidden;
        }

        .fly-word {
            position: absolute;
            left: 100%;
            visibility: hidden;
            /* 设置文字不断，解决中文宽度判断错误 */
            white-space: nowrap;
        }

        .fly-word.out {
            left: 0;
            transition: all 8s linear;
            visibility: visible;
        }

        .input-word {
            border: 2px solid #fa0;
            padding: 0.5em;
            border-radius: 0.5em;
        }

        .input-word,
        .word-btns,
        .use-CSS3-block {
            display: block;
            margin: 1em auto;
            width: 60%;
            text-align: center;
        }

        .input-word,
        .word-btn {
            font-size: 1.5em;
        }

        .word-btn {
            padding: 0.5em 1em;
            cursor: pointer;
        }

        .reset-btn {
            color: #999;
        }

        .use-CSS3-or-not {
            border: 1px solid #ddd;
            font-size: 1.1em;
            padding: 0.5em;
            margin: 0 0.5em;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="screen">
        <!--(div#word-row-$.word-row>span.fly-word{$})*5 -->
        <!-- (div#word-row-$.word-row)*5 -->
        <div id="word-row-1" class="word-row"></div>
        <div id="word-row-2" class="word-row"></div>
        <div id="word-row-3" class="word-row"></div>
        <div id="word-row-4" class="word-row"></div>
        <div id="word-row-5" class="word-row"></div>
    </div>
    <div class="form">
        <form class="form-word" action="#" method="post" onsubmit="submitWord('#input-word','input[name=\'useCSS3\']:checked');return false;">
            <input id="input-word" type="text" class="input-word" name="word" placeholder="请输入弹幕" required autofocus>
            <div class="word-btns">
                <button type="submit" class="word-btn">发射弹幕</button>
                <button type="button" class="word-btn reset-btn" onclick="clearScreen()">清空弹幕</button>
            </div>
            <div class="use-CSS3-block">
                <label for="use-CSS3" class="use-CSS3-or-not">
                    <input id="use-CSS3" type="radio" name="useCSS3" value="true" checked>
                    使用CSS3
                </label>
                <label for="not-use-CSS3" class="use-CSS3-or-not">
                    <input id="not-use-CSS3" type="radio" name="useCSS3" value="false">
                    使用jQuery animate
                </label>
            </div>
        </form>
    </div>
</body>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.wilddog.com/sdk/js/2.3.8/wilddog-sync.js"></script>
<script type="text/javascript">
    var config = {
        syncURL: "https://wild-cock-94365.wilddogio.com" //输入节点 URL
    };
    wilddog.initializeApp(config);
    var ref = wilddog.sync().ref("/web/saving-data/fly-word-wall/words");
    var words = [];
    var _useCSS3 = $('input[name=\'useCSS3\']:checked');
    var showWordIndex = 0;
    var nextShowWordTimer = null;
    ref.on("value", function(snapshot) {
        // console.log(snapshot.val());
        words = snapshot.val() || [];
        var wordsLen = words.length;

        var nextShowWord = function(index) {
            // console.log(index);
            if (index > wordsLen - 1) {
                nextShowWordTimer = null;
                return null;
            } else {
                showWordIndex = index;
                sendWord(words[index], _useCSS3.val() == 'true');
                nextShowWordTimer = setTimeout(function() {
                    nextShowWord(index + 1)
                }, tool.randomInt(300, 700));
            }
        }
        if (wordsLen < 1) {
            return;
        } else if (wordsLen > 10) {
            var overabundance = wordsLen - 10;
            // console.log(overabundance);
            words.splice(0, overabundance);
            if (showWordIndex - overabundance + 1 > 0) {
                showWordIndex = showWordIndex - overabundance + 1;
            } else {
                showWordIndex = 0;
            }
            tool.setRemoteWords(words);
        } else {
            if (nextShowWordTimer !== null) {
                clearTimeout(nextShowWordTimer);
            }
            nextShowWord(showWordIndex);
        }
    });
    var tool = {
        randomInt: function(max, min) {
            min = min || 0;
            if (max < min) {
                var t = min;
                min = max;
                max = t;
            }
            return Math.floor(Math.random() * (max - min + 1)) + min;
        },
        randomColor: function() {
            return "rgb(" + tool.randomInt(255) + "," + tool.randomInt(255) + "," + tool.randomInt(255) + ")";
        },
        randomColorHsl: function() {
            return "hsl(" + tool.randomInt(360) + "," + tool.randomInt(100) + "%," + (tool.randomInt(80) + 0) + "%)";
        },
        sendRemoteWord: function(word) {
            words.push(word);
            ref.set(words);
        },
        setRemoteWords: function(words) {
            ref.set(words);
        }
    }
    var count = 0;
    var sendWord = function(word, useCSS3) {
        count++;
        if (count > 5) {
            count = 1;
        }
        // console.log(count);
        var _newWord = $('<span class="fly-word">' + word + '</span>')
            .css("color", tool.randomColorHsl())
            .appendTo($("#word-row-" + count));
        var newWordWidth = _newWord.width();
        if (useCSS3) {
            setTimeout(function() {
                // 需要等元素绘制到页面了再加class，否则不执行动画
                // 动画多了，60毫秒还是会挂的
                _newWord
                    .addClass("out")
                    .css({
                        left: -newWordWidth
                    })
                setTimeout(function() {
                    // 动画结束移除元素，避免浏览器性能降低
                    _newWord
                        .remove();
                }, 8000);
            }, 60);
        } else {
            _newWord
                .css({
                    // 百分比是相对父元素的
                    'left': '100%',
                    "visibility": "visible"
                })
                .animate({
                    'left': -newWordWidth
                }, tool.randomInt(8000, 10000), 'linear', function() {
                    // 动画结束移除元素，避免浏览器性能降低
                    _newWord
                        .remove();
                });
        }
    }
    var submitWord = function(targetSelector, useCSS3Selector) {
        var _word = $(targetSelector);
        var _useCSS3 = $(useCSS3Selector);
        // console.log(_useCSS3.val());
        // sendWord(_word.val(), _useCSS3.val() == 'true');
        tool.sendRemoteWord(_word.val());
        _word
            .val('')
            .focus();
        return false;
    }
    var clearScreen = function() {
        console.log('clearScreen');
        $(".fly-word")
            .remove();
    }
    $(function() {
        function sendTest() {
            sendWord(tool.randomInt(9), $('input[name="useCSS3"]:checked').val() == 'true');
            // setTimeout(sendTest, Math.random() * 200);
            setTimeout(sendTest, 100);
        }
        // sendTest();
    })
</script>

</html>
